//
//  HMStatusRetweetView.swift
//  Weibo12
//
//  Created by HM on 15/12/31.
//  Copyright © 2015年 itheima. All rights reserved.
//

import UIKit
import SnapKit

class HMStatusRetweetView: UIView {
    
    // 记录当前控件的底部约束
    var bottomConstraint: Constraint?
    
    // 当前转发微博的显示的 model
    var statusViewModel: HMStatusViewModel? {
        didSet{
            contentLabel.text = statusViewModel?.retweetStatusText
            
            // 卸载掉之前的约束
            bottomConstraint?.uninstall()
            // 在设置数据的时候，根据转发微博里面是否有图片，去显示或者隐藏配图控件
            if let picUrls = statusViewModel?.status?.retweeted_status?.pic_urls where picUrls.count > 0 {
                statusPictureView.hidden = false
                // 设置要显示的数据
                statusPictureView.picUrls = picUrls
                // 更新转发微博整体View的底部约束为配图视图的底部
                self.snp_updateConstraints(closure: { (make) -> Void in
                    bottomConstraint = make.bottom.equalTo(statusPictureView.snp_bottom).offset(HMStatusCellMargin).constraint
                })
            }else {
                statusPictureView.hidden = true
                // 更新转发微博整体View的底部约束为内容视图的底部
                self.snp_updateConstraints(closure: { (make) -> Void in
                    bottomConstraint = make.bottom.equalTo(contentLabel.snp_bottom).offset(HMStatusCellMargin).constraint
                })
            }
        }
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    private func setupUI(){
        backgroundColor = UIColor(white: 0.97, alpha: 1)
        
        addSubview(contentLabel)
        addSubview(statusPictureView)
        // 添加约束
        contentLabel.snp_makeConstraints { (make) -> Void in
            make.leading.equalTo(self).offset(HMStatusCellMargin)
            make.top.equalTo(self).offset(HMStatusCellMargin)
            make.width.lessThanOrEqualTo(self.snp_width).offset(2 * -HMStatusCellMargin)
        }
        
        // 添加配图的约束
        statusPictureView.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(contentLabel.snp_bottom).offset(HMStatusCellMargin)
            make.leading.equalTo(contentLabel)
        }
        
        self.snp_makeConstraints { (make) -> Void in
            self.bottomConstraint = make.bottom.equalTo(statusPictureView).offset(HMStatusCellMargin).constraint
        }
    }
    
    
    // MARK: - 懒加载
    
    // 内容的控件
    private lazy var contentLabel: UILabel = {
        let label = UILabel(textColor: UIColor.darkGrayColor(), fontSize: 15)
        // 多行
        label.numberOfLines = 0
        return label
    }()
    
    // 配图视图
    private lazy var statusPictureView: HMStatusPictureView = {
        let pictureView =  HMStatusPictureView()
        pictureView.backgroundColor = self.backgroundColor
        return pictureView
    }()
    
}
